<style lang="less">
  .noticeContBigBox{
    .el-form-item{
      .formInputWidth{
        width: 40%;
        min-width: 300px;
      }
      .el-button{
        margin-top: 2rem;
        width: 13rem;
        margin-right: 2rem;

      }
      .el-button--default{
        color: #63c5ce;
        border-color: #63c5ce;

      }
    }
    .articleCont{
      height: 300px;
      display: inline-block;
      overflow: auto;
      border-radius: 4px;
      border: 1px solid rgb(191, 212, 217);
      width: 60%;

    }
  }

</style>

<template>
  <div class="noticeContBigBox">
    <el-form 
    v-loading="formLoading" 
    element-loading-text="数据请求中"
    :model="formData" 
    :rules="rules" 
    ref="ruleForm" 
    label-width="100px" 
    class="demo-ruleForm">
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="formData.title" class="g-formInputWidth formInputWidth" v-if='this.$route.name=="addNewNotice" || formData.status =="DRAFT"'></el-input>
        <span v-if='this.$route.name =="editNotice" && formData.status !="DRAFT"'>{{formData.title}}</span>
      </el-form-item>

      <el-form-item label="副标题" prop="subTitle">
        <el-input type='textarea' v-model="formData.subTitle" class="g-formInputWidth formInputWidth" v-if='this.$route.name=="addNewNotice" || formData.status =="DRAFT"'></el-input>
        <span v-if='this.$route.name =="editNotice" && formData.status !="DRAFT"'>{{formData.subTitle}}</span>
      </el-form-item>

      <el-form-item label="公告正文" prop="cont" v-if='showRichTextBox'>
        <rich-text-box
        v-model='formData.cont'
        :id='"noticeCont"'
        ></rich-text-box>
      </el-form-item>

      <el-form-item label="公告正文" v-if='!showRichTextBox' >
        <span class="articleCont" v-html='formData.content'></span>
      </el-form-item>

      <el-form-item label="发布终端" prop="">
        <el-checkbox-group v-model="publish" @change='handlePublish'>
          <el-checkbox label="华财通" ></el-checkbox>
          <el-checkbox label="理财师" ></el-checkbox>
          <el-checkbox label="PC" ></el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="首页展示" prop="">
        <el-checkbox-group v-model="top" @change='handleTop'>
          <el-checkbox label="华财通" ></el-checkbox>
          <el-checkbox label="理财师" ></el-checkbox>
          <el-checkbox label="PC" ></el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item v-if='this.$route.name=="addNewNotice" || formData.status =="DRAFT"'>
        <el-button :loading="saveLoading" @click="clickSave" >保存为草稿</el-button>
        <el-button type="primary" :loading="publishLoading" @click="clickPublish">发布</el-button>
      </el-form-item>

      <el-form-item v-if='this.$route.name=="editNotice" && formData.status !="DRAFT"'>
        <el-button type="primary" :loading="publishLoading" @click="clickPublish">保存更新</el-button>
      </el-form-item>
      
    </el-form>

  </div>
</template>

<script>
  import richTextBox from 'components/tinymce'
  import {getNoticeDetail, postCreatNewNotice, postUpdatehNotice} from 'api/noticeManage/index.js'
  import {formRules, emptyCont} from '../config.js'
  export default {
    components:{
      richTextBox,
    },
    data(){
      return{
        uuid:this.$route.query && this.$route.query.id ? this.$route.query.id :'',
        publish:[],//发布终端选择框的值
        top:[],//首页展示选择框的值
        formData:{//提交表单的值
          cont:'111',//这里不能为空，因为表单验证这里是必填项！但是真正判断是否有输入正文是在 submitForm 方法中！
          title:'',
          subTitle:'',//副标题，安卓客户端推送专用
          content:'',
        },
        rules:formRules,
        formLoading:false,//编辑时请求数据加载
        saveLoading:false,
        publishLoading:false,
        showRichTextBox:false,
      }
    },
    methods:{
      setCheckboxVal(name, obj){
        // console.log('setCheckboxVal', name, obj)
        let tempArr =[]
        for(let x in obj){
          if(x =='华财通' && obj[x]=='YES'){
            tempArr.push('华财通')
          }else if(x =='理财师' && obj[x]=='YES'){
            tempArr.push('理财师')
          }else if(x =='PC' && obj[x]=='YES'){
            tempArr.push('PC')
          }
        }
        this[name]=tempArr;
      },
      async getNoticeDetail(id){
        try{
          this.formLoading = true;
          let back = await getNoticeDetail(id)
          back = back.data;
          console.log('getNoticeDetail', back)
          if(back && back.resultCode=='200'){
            Object.assign(this.formData, back.result)
            let publishCheckbox ={
              '华财通':back.result.toHuaCaiTong,
              '理财师':back.result.toLiCaiShi,
              'PC':back.result.toPC,
            }
            let topCheckbox ={
              '华财通':back.result.onTopHuaCaiTong,
              '理财师':back.result.onTopLiCaiShi,
              'PC':back.result.onTopPC,
            }
            this.setCheckboxVal('publish', publishCheckbox)
            this.setCheckboxVal('top', topCheckbox)
            /*已推送的不能修改正文！无富文本框！*/
            this.showRichTextBox = this.$route.name == 'addNewNotice' || (this.$route.name == 'editNotice' && back.result.status != "PUSHED") ?true : false
            if(this.showRichTextBox){
              setTimeout(()=>{
                /*这里需要优化成监听富文本渲染成功在塞数据*/
                this.setRichTextCont(back.result && back.result.content)
                this.formLoading = false;
              },1000)
            }else{
              this.formLoading = false;
            }
          }else{
            this.formLoading = false;
          }
        }catch(err){
          this.formLoading = false;
          this.$alert('获取失败！')
          console.error(err)
        }
      },
      setRichTextCont(msg){
        if(msg && tinymce.get('noticeCont')){
          tinymce.get('noticeCont').setContent(msg)
        }
      },
      handlePublish(val){
        // console.log('handlePublish', val)
        let tempObj={
          toHuaCaiTong:'NO',
          toLiCaiShi:'NO',
          toPC:'NO',
        }
        for(let x in val){
          if(val[x]=='华财通'){
            tempObj.toHuaCaiTong = 'YES'
          }else if(val[x]=='理财师'){
            tempObj.toLiCaiShi = 'YES'
          }else if(val[x]=='PC'){
            tempObj.toPC = 'YES'
          }
        }
        Object.assign(this.formData, tempObj)
        //选择推送给首页就一定要选择发布,这里是为了删除首页的选择
        for(let i in this.top){
          if(!this.publish.includes(this.top[i])){
            this.top.splice(this.top.indexOf(this.top[i]),1)
          }
        }

      },
      handleTop(val){
        // console.log('handleTop', val)
        let tempObj={
          onTopHuaCaiTong:'NO',
          onTopLiCaiShi:'NO',
          onTopPC:'NO',
        }
        for(let x in val){
          if(!this.publish.includes(val[x])){
            //选择推送给首页就一定要选择发布，这里是为了增加发布的选择
            this.publish.push(val[x])
          }
          if(val[x]=='华财通'){
            tempObj.onTopHuaCaiTong = 'YES'
          }else if(val[x]=='理财师'){
            tempObj.onTopLiCaiShi = 'YES'
          }else if(val[x]=='PC'){
            tempObj.onTopPC = 'YES'
          }
        }
        Object.assign(this.formData, tempObj)
        
      },
      getRichTextCont(){
        if(tinymce.get('noticeCont')){
          let cont = tinymce.get('noticeCont').getContent();
          return cont;
        }
      },
      spliceParams(){//创建/更新的接口入参处理
        let tempCheckbox ={
          /*设置 发布/推送 的数据*/
          toHuaCaiTong:this.publish.includes('华财通') ?'YES':'NO',
          toLiCaiShi:this.publish.includes('理财师') ?'YES':'NO',
          toPC:this.publish.includes('PC') ?'YES':'NO',
          onTopHuaCaiTong:this.top.includes('华财通') ?'YES':'NO',
          onTopLiCaiShi:this.top.includes('理财师') ?'YES':'NO',
          onTopPC:this.top.includes('PC') ?'YES':'NO',
        }
        this.formData.content = tinymce.get('noticeCont') ? this.getRichTextCont() : this.formData.content;
        Object.assign(this.formData , tempCheckbox)
      },
      submitForm(){
        let result;
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if(this.$route.name=="addNewNotice" || (this.$route.name=="editNotice" && this.formData.status !="PUSHED")){
              let cont = this.getRichTextCont();
              if(cont != emptyCont){
                result = true
              }else{
                this.$alert('请输入正文')
                return false
              }
            }else{
              result = true
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
        return result;
      },
      clickSave(){
        if(this.publishLoading || this.saveLoading)return
        if(this.submitForm()){
          this.spliceParams()
          this.saveLoading= true;
          this.ajaxFun('DRAFT')
          
        }
      },
      clickPublish(){
        if(this.publishLoading || this.saveLoading)return
        if(this.submitForm()){
          this.spliceParams()
          this.publishLoading= true;
          this.ajaxFun('PUBLISHED')
        }
      },
      async ajaxFun(status){
        try{
          if(!status) return
          let back;
          let params = {
            status : status,
            author:sessionStorage.getItem('realName')?sessionStorage.getItem('realName'):sessionStorage.getItem('USER_NAME'),
          }
          params = Object.assign({},this.formData, params)
          if(this.$route.name =="editNotice"){
            back = await postUpdatehNotice(params)
          }else if(this.$route.name =="addNewNotice"){
            back = await postCreatNewNotice(params)
          }
          back= back.data
          this.saveLoading= false;
          this.publishLoading= false;
          if(back && back.resultCode == '200'){
            await this.$alert('成功！',{
              callback: action =>{
                this.goPage('noticeList')
                this.$emit('reloadPage')
              }
            })
          }else{
            this.$alert(back.msg)
          }
        }catch(err){
          this.saveLoading= false;
          this.publishLoading= false;
          this.$alert('提交失败！请稍后重试')
          console.error(err)
        }

      },
      setTitleMsg(msg){
        this.$emit('setTitleMsg', msg)
      },
      goPage(name){
        this.$router.push({
          name:name
        })
      }

    },
    created(){
      if(this.$route.query && this.$route.query.id){
        this.getNoticeDetail(this.$route.query.id)
        this.setTitleMsg(['公告管理', '公告列表','编辑公告'])
      }else{
        this.showRichTextBox =true;
        this.setTitleMsg(['公告管理', '公告列表','发布公告'])
      }
    },
    destroyed() {
      this.setTitleMsg(['公告管理', '公告列表'])
    }
    
    
  }
</script>
